<?php


namespace app\miniapp\controller\v2;


use app\astro\controller\Data;
use app\astro\controller\MiniAppSignscore;
use app\common\cachemodel\Astro;
use app\common\cachemodel\NatalGoods;
use app\common\cachemodel\Recode;
use app\common\lib\ConfigManage;
use app\common\lib\exception\ApiException;
use app\common\lib\Natal;
use app\common\lib\Util;
use app\common\model\Orders;
use app\miniapp\controller\v1\Auth;
use think\Env;
use XznsTools\cache\CacheManage;
use app\miniapp\model\MiniVersion;

class Index extends Auth
{
    /**
     * 首页
     * @throws \Exception
     */
    public function index()
    {
        $rid = input('rid/s', '');
        $type = input('type/d', 0);
        $now_time = time();

        if ($this->miniInfo && !$rid)
        {
            throw new ApiException('服务异常，档案缺失', 200, 406);
        }
        $NatalReportModel = new \app\common\cachemodel\NatalReport();
        if ($this->user)
        {   // 已登陆获取档案信息
            $recodeInfo = (new Recode())->getInfoById($rid);
            if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '请求异常,档案不存在');
            }
            // 获取购买商品状态
            // 获取解锁订单信息状态
            $unlockReport = $NatalReportModel->getNatalReport2($recodeInfo);
            // $unlockReport = $NatalReportModel->getNatalReport($this->user['id'], $rid);
        } else
        {   // 未登陆获取档案信息
            $recodeInfo = [];
            $unlockReport = [];
        }

        //  获取分数及词条
        $natal = $recodeInfo ? (new Natal())->getScoreAndText($recodeInfo) : [];
        //  获取本命预测商品信息
        $goodType = $this->headers['app-type'] === 'TT' ? 13 : 7; // 抖音小程序获取的为精简版本命报告 7=>完整版本命报告 13=>精简版本命报告
        $goodData = (new NatalGoods())->getGoods($goodType);

        $gData = [];
        foreach ($goodData as $gitem)
        {
            $ks = (string)($gitem['is_recommend_index'] * 100000000 + $gitem['sort'] + ('0.' . $gitem['id']));
            $gData[$ks] = $gitem;
        }
        krsort($gData);

        $oldNatalScore = ['feelings' => 'love', 'dating' => 'home', 'carrer' => 'work', 'money' => 'money', 'academic' => 'study'];
        $goodBtnCollor = [
            'feelings' => [ // 恋爱
                'btn_color' => '#FF6C89',
                'num_color' => '#FF8FAC',
                'num_bg_color' => '#FFC6D3',
            ],
            'dating' => [ // 婚姻
                'btn_color' => '#32C4FE',
                'num_color' => '#32C3FD',
                'num_bg_color' => '#ABE0FA',
            ],
            'carrer' => [ // 事业
                'btn_color' => '#6546F5',
                'num_color' => '#6546F4',
                'num_bg_color' => '#C8C2F8',
            ],
            'money' => [ // 财富
                'btn_color' => '#FFBA07',
                'num_color' => '#FEB907',
                'num_bg_color' => '#FBE19F',
            ],
            'academic' => [ // 学业
                'btn_color' => '#256AFD',
                'num_color' => '#4B93FF',
                'num_bg_color' => '#CEE0FC',
            ]
        ];
        $natalReportList = [];
        $goodList = [];
        $goodRecommend = [];
        $unlockNatalReportNum = 0;
        $orderModel = new \app\common\cachemodel\Orders();
        if ($this->headers['app-type'] === 'TT')
        {   // 抖音小程序获取精简版的商品图片
            $natalReportImg = ConfigManage::simNatalReportGoodImage();
        } else
        {   //  完整版解锁图片
            $natalReportImg = ConfigManage::natalReportGoodImage(2);
        }
        foreach (array_values($gData) as $key => $item)
        {
            if ($natal)
            {
                $d = [
                    'gid' => (int)$item['id'],
                    'score' => $natal[$oldNatalScore[$item['flag']]] ?? 0,
                    'gcolor' => $item['color'] ?? '',
                    'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
                ];

                $natalReportList[] = $d;
            }
            $unlock_num = 0;
            if ($item['status'] != 2)
            {
                $unlock_num = $item['base_num'] + $orderModel->getTotalPrepaidOrder($goodType, $item['id']);
                $unlockNatalReportNum += $unlock_num;
            }

            if ($item['status'] == 2 || ($type === 0 && !$item['is_recommend_index']))
            {   // 如果是首页 并且 没有推荐到首页
                continue;
            } else//判断商品解锁状态
            {
                if (isset($unlockReport[$item['id']]))
                {
                    $unlock_status = (int)$unlockReport[$item['id']]['status'] === 2 ? 2 : 1;
                    $status = isset($unlockReport[$item['id']]) ? ($unlock_status) : 0;
                } else
                {
                    $status = (int)($item['status'] == 1 ? 0 : 3);
                }
            }

            // TODO 学业报告临时活动
            if ((int)$item['id'] === 52 && $now_time >= 1595498400 && $now_time <= 1599321599)
                // if ((int)$item['id'] === 52 && $now_time >= 1595433600 && $now_time <= 1599321599) // 测试代码
            {
                $bgImg = $natalReportImg['large_active'][$item['flag']];
            } else
            {
                // todo 暂时默认全部长图
                $bgImg = $natalReportImg['large'][$item['flag']];
            }

            $gData = [
                'status' => $status,
                'bg_img' => $bgImg,
                'unlock_num' => $status === 3 ? 0 : $unlock_num,
                'type' => 0,
                'btn_color' => $goodBtnCollor[$item['flag']]['btn_color'] ?? '',
                'num_color' => $goodBtnCollor[$item['flag']]['num_color'] ?? '',
                'num_bg_color' => $goodBtnCollor[$item['flag']]['num_bg_color'] ?? '',
                'gid' => (int)($item['id'] ?? 0)
            ];

            //获取后台小程序版本号管理中的微信小程序商品按钮信息
            if ($this->headers['app-type'] === 'WEAPP' && (isset($this->headers['os']) && $this->headers['os'] === 'ios'))
            {
                $MiniVersion = new MiniVersion();
                $map = [
                    'version_id' => $this->headers['version'],
                    'mini_type' => 'WEAPP',
                    'app_type' => 1,
                    'status' => 1
                ];
                $version_info = [];
                try
                {
                    $version_info = $MiniVersion->getMiniAppBtnInfo($map, ['weapp_btn_desc']);
                }
                catch (\Exception $e)
                {
                }
            }

            //如果是微信环境
            if ($this->headers['app-type'] === 'WEAPP' && (isset($this->headers['os']) && $this->headers['os'] === 'ios') && $status != 2 && !empty($version_info['weapp_btn_desc']))
            {
                $gData['status'] = 4;
                $gData['btn_desc'] = $version_info['weapp_btn_desc'] ?? '由于相关规范，iOS功能暂不可用';
                $gData['btn_hint'] = $version_info['weapp_btn_desc'] ?? '由于相关规范，iOS功能暂不可用';
            }

            if ($item['is_recommend_index'])
            {
                $goodRecommend[] = $gData;
            } else
            {
                $goodList[] = $gData;
            }
        }

        $goodList = array_merge($goodRecommend, $goodList);

        $goodContent = [];

        $tt_mini_version_info = [];
        if ($goodList)
        {
            //如果是TT环境首页
            if ($this->headers['app-type'] === 'TT')
            {
                $where = [
                    'version_id' => $this->headers['version'],
                    'mini_type' => 'TT',
                    'app_type' => '1',
                    'status' => 1
                ];
                try
                {
                    $tt_mini_version_info = (new MiniVersion())->getMiniAppTtHintInfo($where);
                }
                catch (\Exception $e)
                {

                }
                if ($type === 0)
                { // 首页
                    $goodContent[] = [
                        'title' => '专属预测报告',
                        // 'desc' => $tt_mini_version_info['tt_goods_desc'] ?? '一次购买、终生免费升级',
                        'desc' => $tt_mini_version_info['tt_goods_desc'] ?? '',
                        'goods_list' => $goodList
                    ];
                } else
                { // 深度预测页面
                    $goodContent[] = [
                        'title' => '深度预测报告',
                        // 'desc' => $tt_mini_version_info['tt_goods_desc'] ?? '点击可查看得分意义',
                        'desc' => $tt_mini_version_info['tt_goods_desc'] ?? '',
                        'goods_list' => $goodList
                    ];
                }
            } else
            {
                if ($type === 0)
                { // 首页
                    $goodContent[] = [
                        'title' => '专属预测报告',
                        // 'desc' => '一次购买、终生免费升级',
                        'desc' => '',
                        'goods_list' => $goodList
                    ];
                } else
                { // 深度预测页面
                    $goodContent[] = [
                        'title' => '深度预测报告',
                        // 'desc' => '点击可查看得分意义',
                        'desc' => '',
                        'goods_list' => $goodList
                    ];
                }
            }
        }


        $signScore = null;
        if ($type === 0)
        {   // 首页
            if ($this->headers['app-type'] === 'TT')
            { // 抖音小程序 获取精简版的商品数据
                $goodContent[] = [
                    'title' => '详细运势报告',
                    // 'desc' => $tt_mini_version_info['tt_goods_desc'] ?? '一次购买、终生免费升级',
                    'desc' => $tt_mini_version_info['tt_goods_desc'] ?? '',
                    'goods_list' => [
                        [
                            'status' => 0,
                            'bg_img' => '/test/natal_report/mini_tt/type_fortune_month.png',
                            'unlock_num' => (new  Orders())->getSimFortuneOrderNum(),
                            'type' => 12, // 精简版月运
                            'btn_color' => '#FA8C00',
                            'num_color' => '#FA6400',
                            'num_bg_color' => '#FDCDA3',
                            'gid' => -1
                        ]
                    ]
                ];
                $goodContent[] = [
                    'title' => '深度预测报告',
                    // 'desc' => $tt_mini_version_info['tt_goods_desc'] ?? '一次购买、终生免费升级',
                    'desc' => $tt_mini_version_info['tt_goods_desc'] ?? '',
                    'goods_list' => [
                        [
                            'status' => 0,
                            'bg_img' => '/test/natal_report/mini_tt/type_natal_report.png',
                            'unlock_num' => $unlockNatalReportNum,
                            'type' => 13, // 精简版本命报告
                            'btn_color' => '#44D7B6',
                            'num_color' => '#44D7B6',
                            'num_bg_color' => '#BCF0E4',
                            'gid' => -1
                        ]
                    ]
                ];
            } elseif ($this->headers['app-type'] === 'WEAPP' && (isset($this->headers['os']) && $this->headers['os'] === 'ios') && !empty($version_info['weapp_btn_desc']))
            {
                $goodContent[] = [
                    'title' => '详细运势报告',
                    // 'desc' => '一次购买、终生免费升级',
                    'desc' => '',
                    'goods_list' => [
                        [
                            'status' => 2,
                            'bg_img' => '/mini/astrolabe/goods/type_fortune_month.png?v=52672282',
                            'unlock_num' => (new  Orders())->fortune_base(['type' => 1]),
                            'type' => 3,
                            'btn_color' => '#FA8C00',
                            'num_color' => '#FA6400',
                            'num_bg_color' => '#FDCDA3',
                            'gid' => -1,
//                            'btn_desc' => $version_info['weapp_btn_desc'] ?? '由于相关规范，iOS功能暂不可用',
//                            'btn_hint' => $version_info['weapp_btn_desc'] ?? '由于相关规范，iOS功能暂不可用'
                        ]
                    ]
                ];
                $goodContent[] = [
                    'title' => '深度预测报告',
                    // 'desc' => '一次购买、终生免费升级',
                    'desc' => '',
                    'goods_list' => [
                        [
                            'status' => 4,
                            'bg_img' => '/mini/astrolabe/goods/type_natal_report.png?v=52672282',
                            'unlock_num' => $unlockNatalReportNum,
                            'type' => 7,
                            'btn_color' => '#44D7B6',
                            'num_color' => '#44D7B6',
                            'num_bg_color' => '#BCF0E4',
                            'gid' => -1,
                            'btn_desc' => $version_info['weapp_btn_desc'] ?? '由于相关规范，iOS功能暂不可用',
                            'btn_hint' => $version_info['weapp_btn_desc'] ?? '由于相关规范，iOS功能暂不可用'
                        ]
                    ]
                ];
            } else
            {
                $goodContent[] = [
                    'title' => '详细运势报告',
                    // 'desc' => '一次购买、终生免费升级',
                    'desc' => '',
                    'goods_list' => [
                        [
                            'status' => 0,
                            'bg_img' => '/mini/astrolabe/goods/type_fortune_month.png?v=52672282',
                            'unlock_num' => (new  Orders())->fortune_base(['type' => 1]),
                            'type' => 3,
                            'btn_color' => '#FA8C00',
                            'num_color' => '#FA6400',
                            'num_bg_color' => '#FDCDA3',
                            'gid' => -1
                        ]
                    ]
                ];
                $goodContent[] = [
                    'title' => '深度预测报告',
                    // 'desc' => '一次购买、终生免费升级',
                    'desc' => '',
                    'goods_list' => [
                        [
                            'status' => 0,
                            'bg_img' => '/mini/astrolabe/goods/type_natal_report.png?v=52672282',
                            'unlock_num' => $unlockNatalReportNum,
                            'type' => 7,
                            'btn_color' => '#44D7B6',
                            'num_color' => '#44D7B6',
                            'num_bg_color' => '#BCF0E4',
                            'gid' => -1
                        ]
                    ]
                ];
            }

            if ($recodeInfo)
            {
                // 获取星座成分
                $signScore = [
                    'title' => '星座成分',
                    'score' => [],
                ];
                $totalScore = $this->getTotalScore($recodeInfo);
                $utilModel = new Util();
                foreach ($totalScore['sign_score'] as $value)
                {
                    $planet_name = [];
                    foreach ($value['in_sign'] as $item)
                    {
                        $planet_id = (int)$item['id'];
                        $planet_info = mb_substr($utilModel->PlanetTypeName($planet_id), 0, 1);
                        if ($planet_info === '太')
                        {
                            $planet_info = '日';
                        } elseif ($planet_info === '上')
                        {
                            $planet_info = '升';
                        }
                        $planet_name[] = $planet_info;
                    }
                    $signScore['score'][] = [
                        'sign_id' => $value['id'],//星座id
                        'planets_name_list' => $planet_name,//行星名称列表
                        'percent' => round($value['percent'], 2),//占比
                        'tags' => $value['tags']//标签
                    ];
                }
            }
        }

        $hasPayOrder = $this->user ? (new \app\miniapp\common\Order())->getRecodeHasOrderPay((int)$this->user['id'], (int)$rid) : false;

        if ($recodeInfo)
        {
            $utilModel = new Util();
            $sun = mb_substr($utilModel->recodeAstro($recodeInfo['sun']), 0, 2);
            $moon = mb_substr($utilModel->recodeAstro($recodeInfo['moon']), 0, 2);
            $asc = mb_substr($utilModel->recodeAstro($recodeInfo['asc']), 0, 2);

            $resData = [
                'recode' => [
                    'name' => $recodeInfo['name'],
                    'type' => $recodeInfo['type'],
                    'year' => $recodeInfo['year'],
                    'month' => $recodeInfo['month'],
                    'day' => $recodeInfo['day'],
                    'hour' => $recodeInfo['hour'],
                    'minute' => $recodeInfo['minute'],
                    'birth_country' => $recodeInfo['birth_country'],
                    'birth_province' => $recodeInfo['birth_province'],
                    'birth_city' => $recodeInfo['birth_city'],
                    'live_country' => $recodeInfo['live_country'],
                    'live_province' => $recodeInfo['live_province'],
                    'live_city' => $recodeInfo['live_city'],
                    'comments' => $recodeInfo['comments'],
                    'long_deg' => $recodeInfo['long_deg'],
                    'long_min' => $recodeInfo['long_min'],
                    'ew' => $recodeInfo['ew'],
                    'lat_deg' => $recodeInfo['lat_deg'],
                    'lat_min' => $recodeInfo['lat_min'],
                    'ns' => $recodeInfo['ns'],
                    'avatar' => $recodeInfo['avatar'] ?? '',
                    'rid' => $rid,
                    'info' => '日' . $sun . '·月' . $moon . '·升' . $asc
                ],
                'astro_explain_url' => Env::get('host.domain') . '/miniweb/v1/astro_explain?rid=' . $rid,
                'sign_score' => $signScore, // 星座成分
                'natal_report_list' => $natalReportList,
                'goods_content' => $goodContent,
                'uen' => $this->user['uen'] ?? '',
                'is_show_contact' => $hasPayOrder ? 1 : 0,
            ];
        } else
        {
            $resData = [
                'recode' => null,
                'astro_explain_url' => null,
                'sign_score' => null, // 星座成分
                'natal_report_list' => null,
                'goods_content' => $goodContent,
                'uen' => '',
                'is_show_contact' => 0,
            ];
        }

        if ($this->headers['app-type'] === 'TT')
        {
            if (0 == $type)
            {
                $resData['tt_share_data'] = config('miniapp_tt_share.index');
            } else if (1 == $type)
            {
                $resData['tt_share_data'] = config('miniapp_tt_share.natal_report_index');
            }
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     *  获取人生分数
     * @param $recodeInfo 档案信息
     * @return array
     * @throws \app\common\lib\exception\ApiException
     * @throws \Exception
     */
    protected function getTotalScore($recodeInfo)
    {
        $date = date('Ymd');
        $resData = CacheManage::getInstance()->setCacheConfig('miniapp.total_score', $recodeInfo['id'] . ':' . $date)->getDataAndSet(function () use ($recodeInfo)
        {
            $Data = new Data();

            $AstroModel = new Astro();

            $timestamp1 = $Data->deal_time($recodeInfo);

            $utdatenow = strftime('%d.%m.%Y', $timestamp1);
            $utnow = strftime('%H:%M:%S', $timestamp1);

            $longitude = ($recodeInfo['long_deg'] + $recodeInfo['long_min'] / 60) * $recodeInfo['ew'];
            $latitude = ($recodeInfo['lat_deg'] + $recodeInfo['lat_min'] / 60) * $recodeInfo['ns'];

            $Data->planets_display = '111111111100100001001';
            $Data->asps_display = [0, 60, 90, 120, 180];
            $Data->asp_orb_all = [0 => 8, 60 => 6, 90 => 7, 120 => 7, 180 => 7, 30 => 1, 150 => 2, 45 => 2, 135 => 2, 72 => 2, 144 => 2];
            $Data->planet_orb_all = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            $hys = 'p';

            $options = ['utdatenow' => $utdatenow, 'utnow' => $utnow, 'longitude' => $longitude, 'latitude' => $latitude, 'h_sys' => $hys];

            $out = $Data->execData($options);

            $original_data = $Data->getOriginalData($out, $hys);
            $Data->array_remove($original_data, $Data->planets_display);
            $details = $Data->getPlanetHouseDetail($original_data, $original_data['hc1'], $recodeInfo['year']);

            $phase = $Data->planetPkPlanet($original_data, $original_data, true);
            foreach ($phase['planets'] as $k => $d)
            {
                $details['planets'][$k]['phase'] = $d['phase'];
                if (empty($d['phase'])) $details['planets'][$k]['phase'] = null;
            }

            $details['phase'] = $phase['phase'];
            $details['characteristic'] = $Data->recept_or_mutual_recept($details['planets']);

            $details = $AstroModel->get_structure($details);

            $data = [];
            $SignscoreModel = new MiniAppSignscore($details);
            // $PlanetpowerModel = new Planetpower($details);
            $data['sign_score'] = json_encode($SignscoreModel->_initload($recodeInfo), JSON_UNESCAPED_UNICODE);
            // $data['planet_power'] = $PlanetpowerModel->_initload();

            return $data;
        });

        foreach ($resData as $key => $valueStr)
        {
            $resData[$key] = json_decode($valueStr, true);
        }

        return $resData;
    }
}
